<!--
* @Author: XieQiu 雪球
* @Date: 2021-05-10 15:07:49
 * @LastEditTime: 2023-03-02 16:41:45
 * @LastEditors: Please set LastEditors
* @Description:  检验配置管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar :page-no="78" :has-qr="true" :add-active="addActive" :del-active="delActive" :edit-active="editActive"
        :cancel-active="cancelActive" :save-active="saveActive" :has-edit="false" :has-save="false" @add="add"
        @cancel="cancel" @edit="edit" @del="del" @save="save('formData')" />
      <!-- @qrShow="qrShow" -->
    </template>
    <template v-slot:search-box>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="search()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">配置名称</div>
            <el-input v-model="checkConfigName" placeholder="请输入检验配置名称" clearable @input="search" />
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:table-box>
      <el-table ref="tableData" v-loading="loading" :data="tableData" stripe border height="88%" @row-click="handleEdit"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="checkTypeName" label="检验类型" />
        <el-table-column prop="checkConfigName" label="检验配置名称" />
        <el-table-column prop="breedTypeListStr" label="状态">
          <template slot-scope="scope" v-if="scope.row.checkConfigId">
            <span :style="{ color: scope.row.status ? '#67C23A' : '#F56C6C' }">{{ scope.row.status ? '已开启' : '已关闭' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="disposeDateTime" label="配置时间" />
        <el-table-column label="操作" width="200">
          <template v-if="scope.row.checkConfigId" slot-scope="scope">
            <el-button class="text-btn-cursor" type="text" v-if="judgePermission(79, 'edit')" size="small"
              @click="edit(scope.row)">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button class="text-btn-cursor cursor-delete" type="text" size="small" v-if="judgePermission(79, 'delete')"
              @click="handleDelete(scope.row)">
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
    </template>
    <template v-slot:dialog>
      <el-dialog :title="titleText + '检验配置信息'" :visible.sync="dialogFormVisible" :before-close="cancel">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <el-form-item label="检验配置名称 :" prop="checkConfigName" class="w50p">
            <el-input v-model="formData.checkConfigName" placeholder="请输入检验配置名称" clearable />
          </el-form-item>
          <el-form-item label="检验类型 :" prop="checkTypeIdList" class="w50p">
            <el-select filterable clearable v-model="formData.checkTypeIdList" multiple filterable clearable>
              <el-option v-for="(item, index) in detectionList" :key="index" :label="item.checkTypeName"
                :value="item.checkTypeId" />
            </el-select>
          </el-form-item>
          <el-form-item label="配置启停状态:" prop="status" class="w50p">
            <el-switch v-model="formData.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="true"
              :inactive-value="false" active-text="开启" inactive-text="关闭" />
          </el-form-item>
          <el-divider></el-divider>
          <div v-for="itemadd, indexadd in addlist" :key="indexadd + 'indexadd'"
            style="width: 100%;border: 1px solid #00000020;padding: 10px 0; position: relative;margin-bottom: 30px;">
            <div class="input-line" v-if="!itemadd.categoryType">
              <div class="input-line-lab">检验范畴:</div>
              <el-select filterable clearable v-model="itemadd.categoryType" filterable clearable class="input-line-input"
                @change="categoryTypeChange">
                <el-option v-for="(evaluationIndexitem, evaluationIndexindex) in BenumList" :key="evaluationIndexindex"
                  :value="evaluationIndexitem.name" :label="evaluationIndexitem.value" />
              </el-select>
            </div>
            <el-divider v-if="itemadd.categoryType" class="divider" content-position="left">{{
              categoryTypeR(itemadd.categoryType) }}</el-divider>
            <div v-for="(additem, addindex) in itemadd.checkConfigDetailList" :key="addindex" class="input-line">
              <div class="input-two-line">
                <div class="input-line-lab">检验科目:</div>
                <el-input v-model="itemadd.checkConfigDetailList[addindex].checkSubject" class="input-line-input" />
              </div>
              <div class="input-two-line">
                <div class="input-line-lab">检验标准:</div>
                <el-input v-model="itemadd.checkConfigDetailList[addindex].checkStandard" class="input-line-input" />
              </div>
              <div class="input-two-line">
                <div class="input-line-lab">答案类型:</div>
                <el-radio-group v-model="itemadd.checkConfigDetailList[addindex].answerType">
                  <el-radio v-for="(evaluationIndexitem, evaluationIndexindex) in AenumList" :key="evaluationIndexindex"
                    :label="evaluationIndexitem.name">{{ evaluationIndexitem.value }}</el-radio>
                </el-radio-group>
              </div>
              <div v-if="itemadd.checkConfigDetailList[addindex].answerType === 'TWOTERMSTYPE'"
                style="width:100%;margin-left: 90px;" class="input-two-line w100p">
                <el-input v-model="itemadd.checkConfigDetailList[addindex].enumContentList[0]" class="input-line-input"
                  style="width:200px" placeholder>
                  <template slot="prepend">选项一 :</template>
                </el-input>
                <el-input v-model="itemadd.checkConfigDetailList[addindex].enumContentList[1]" class="input-line-input"
                  style="width:200px" placeholder>
                  <template slot="prepend">选项二 :</template>
                </el-input>
                <el-input v-model="itemadd.checkConfigDetailList[addindex].standardValue" style="width:200px">
                  <template slot="prepend">标准值 :</template>
                </el-input>
              </div>
              <div v-if="itemadd.checkConfigDetailList[addindex].answerType === 'LISTTYPE'"
                style="width:100%;margin-left: 90px;" class="input-two-line w100p">
                <el-input v-for="(items, indexs) in itemadd.checkConfigDetailList[addindex].enumContentList" :key="indexs"
                  v-model="itemadd.checkConfigDetailList[addindex].enumContentList[indexs]" class="input-line-input"
                  style="width:200px" placeholder clearable @blur="() => {
                    if (itemadd.checkConfigDetailList[addindex].enumContentList[itemadd.checkConfigDetailList[addindex].enumContentList.length - 1] !== '') {
                      itemadd.checkConfigDetailList[addindex].enumContentList.push('')
                    }
                  }" @clear="() => {
  itemadd.checkConfigDetailList[addindex].enumContentList.splice(indexs, 1)
}" />

                <el-input v-model="itemadd.checkConfigDetailList[addindex].standardValue" style="width:200px"
                  placeholder="标准值" />
              </div>
              <div v-if="itemadd.checkConfigDetailList[addindex].answerType === 'NUMTYPE'" class="w100p input-two-line"
                style="width:100%;margin-left: 90px;">
                <el-input v-model="itemadd.checkConfigDetailList[addindex].upperLimit" class="input-line-input"
                  style="width:200px" placeholder="上限值" />
                <el-input v-model="itemadd.checkConfigDetailList[addindex].lowerLimit" style="width:200px"
                  class="input-line-input" placeholder="下限值" />
                <el-select filterable clearable v-model="itemadd.checkConfigDetailList[addindex].unitName" allow-create filterable clearable
                  style="width:200px" placeholder="单位" class="input-line-input" @change="categoryTypeChange">
                  <el-option v-for="(unitListItem, unitListIndex) in unitList" :key="unitListIndex + 'unit'"
                    :value="unitListItem.unitName" :label="unitListItem.unitName" />
                </el-select>
              </div>
              <div class="line-click" @click="dellineone(addindex, indexadd)"
                v-if="itemadd.checkConfigDetailList.length > 1">
                <i class="el-icon-minus"></i>
              </div>
              <div @click="addlineone(indexadd)" v-if="itemadd.checkConfigDetailList.length - 1 === addindex"
                class="line-click">
                <i class="el-icon-plus"></i>
              </div>
              <el-divider></el-divider>
              <!-- <el-divider></el-divider> -->
            </div>
          </div>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="addlinetwo()">添加检验范畴</el-button>
          <el-button class="zh-button-one" @click="dellinetwo()">删除检验范畴</el-button>
          <el-button class="cancelbtn" @click="cancel('formData')">取 消</el-button>
          <el-button class="savebtn" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import EnumApi from "@/api/enum";
import UnitManageApi from "@/api/basic-info-manage/unit-manage";
import verifyApi from "@/api/inspection-management/verify-configuration";
import detectionApi from "@/api/inspection-management/detection-type-management";
// import SeeEquip from "@/components/seeEquip/index.vue";
export default {
  name: "VerifyConfiguration",
  components: {
    ActionBar,
    Pagination,
    BaseMainSlot
    // SearchBox
    // SeeEquip
  },
  mixins: [mymixin],
  data() {
    return {
      obj: {
        name: ""
      },
      //  检验配置名称
      checkConfigName: "",
      detectionList: [],
      rules: {
        checkConfigName: [
          { required: true, message: "请输入检验配置名称", trigger: "blur" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "blur" }],
      },
      dialogTitle: "",
      dialogFormVisible: false,
      facilityVOList: [],
      AenumList: [],
      BenumList: [],
      unitList: [],
      addlist: [
        {
          // categoryType:"ANATOMYCHECK",
          checkConfigDetailList: [
            {
              enumContentList: ["合格", "不合格"],
              answerType: "TWOTERMSTYPE"
            },
            {
              enumContentList: ["合格", "不合格"],
              answerType: "TWOTERMSTYPE"
            }
          ]
        }
      ],
      isShowEquip: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    // 动态添加数据
    nowChanceStau: {
      deep: true,
      handler(val) {
        if (val === "add") {
          this.$set(this.formData, "status", false);
          this.addlist = [
            {
              checkConfigDetailList: [
                {
                  enumContentList: ["合格", "不合格"],
                  answerType: "TWOTERMSTYPE"
                },
              ]
            }
          ]
        }
        if (val === 'edit') {
          this.formData = this.editObject
          this.formData.checkTypeIdList = [this.formData.checkTypeId]
          const tempList = []
          const tempCheckType = []
          this.formData.checkConfigDetailList.forEach((item, index) => {
            if (tempCheckType.findIndex((item2) => item.categoryType === item2) === -1) {
              tempCheckType.push(item.categoryType)
              tempList.push({ categoryType: item.categoryType, checkConfigDetailList: [] })
            }
          })
          this.formData.checkConfigDetailList.forEach((item, index) => {
            item.enumContentList = item.enumContent.split(',')
            let tempIndex = tempList.findIndex((item2, index2) => item.categoryType === item2.categoryType)
            tempList[tempIndex].checkConfigDetailList.push(item)
          })
          this.addlist = tempList
        }
      }
    }
  },
  created() { },
  mounted() {
    this.search();
    this.queryEnum();
  },
  methods: {
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          checkConfigName: this.checkConfigName || undefined
        }
      };
      verifyApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        let data = res.data;
        // 赋值总条数
        if (data) {
          this.totalSize = data.totalElements;
        }

        // 赋值数组
        this.tableData = [];
        if (data !== undefined) this.tableData = data.content;
        this.addblankmet();
        this.resetActionBar();
      });
    },
    queryEnum() {
      EnumApi.list({ enumType: "AnswerType" }).then(res => {
        this.AenumList = res.data;
      });
      EnumApi.list({ enumType: "CategoryType" }).then(res => {
        this.BenumList = res.data;
      });
      detectionApi.queryByCondition({}).then(res => {
        this.detectionList = res.data;
      });
      UnitManageApi.queryByCondition().then(res => {
        this.unitList = res.data
      })
    },
    categoryTypeChange() {
      this.addlist.forEach((item, index) => {
        if (item.categoryType) {
          item.checkConfigDetailList.forEach(((item2, index2) => {
            this.$set(this.addlist[index].checkConfigDetailList[index2], 'categoryType', this.addlist[index].categoryType)
          }))
        }
      });
    },
    // 添加一条评分标准
    addlineone(index) {
      this.addlist[index].checkConfigDetailList.push({
        enumContentList: [""],
        answerType: "TWOTERMSTYPE",
        categoryType: this.addlist[index].categoryType
      });
    },
    // 删除一条评分标准
    dellineone(index, indexadd) {
      this.addlist[indexadd].checkConfigDetailList.splice(index, 1);
    },
    // 添加一条评分标准
    addlinetwo(e) {
      this.addlist.push({
        checkConfigDetailList: [
          {
            enumContentList: ["合格", "不合格"],
            answerType: "TWOTERMSTYPE"
          },
          {
            enumContentList: ["合格", "不合格"],
            answerType: "TWOTERMSTYPE"
          }
        ]
      });
    },
    // 删除一条评分标准
    dellinetwo() {
      this.addlist.pop();
    },
    categoryTypeR(e) {
      if (e) {
        let answer = this.BenumList.find(item => item.name === e);
        return answer.value;
      }
    },
    handleEdit(row) {
      // // TODO 点击行元素后 edit
      // this.facilityList = [];
      // this.nowfishPondId = "";
      // if (row.checkConfigId) {
      //   this.formData = JSON.parse(JSON.stringify(row));
      //   this.editActive = true;
      //   this.saveActive = false;
      //   this.cancelActive = true;
      //   this.canInput = false;
      // } else {
      //   this.formData = {};
      // }
    },
    handleSelectionChange(list) {
      this.inspectionPointIdList = [];
      this.inspectionPointIdList = list.map(item => item.checkConfigId);
      if (this.inspectionPointIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      verifyApi.delListById({ idList: [this.inspectionPointIdList] }).then(res => {
        if (res.success) {
          this.search();
          this.$message.success(res.message || "删除成功");
          this.facilityList = [];
          this.nowfishPondId = "";
        } else {
          this.$message.warning(res.message || "删除失败");
        }
      });
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          verifyApi.delById({ id: row.checkConfigId }).then(res => {
            if (res.success) {
              this.search();
              this.resetActionBar()
              this.$message.success(res.message || "删除成功");
            } else {
              this.resetActionBar()
              this.$message.warning(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.resetActionBar()
          this.$message("取消删除");
        });
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          // console.log(this.addlist);
          // 将数据处理为接口接收结构
          const tempList = []
          this.addlist.forEach(item => {
            if (item.categoryType) {
              item.checkConfigDetailList.forEach((item2 => {
                tempList.push(item2)
              }))
            }
          });
          this.formData.checkConfigDetailList = tempList
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            verifyApi.add(this.formData).then(res => {
              if (res.success) {
                this.search();
                this.$message.success(res.message || "修改成功！");
              } else {
                this.$message.error(res.message || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            // console.log(this.formData);
            verifyApi.add(this.formData).then(res => {
              if (res.success) {
                this.search();
                this.$message.success(res.message || "新增成功！");
              } else {
                this.$message.error(res.message || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 修改
    edit(row) {
      if (row.checkConfigId) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.addActive = false;
        this.delActive = false;
        this.dialogFormVisible = true;
      } else {
        this.editObject = {};
      }
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-form-item__label {
  min-width: 155px !important;
}

::v-deep .el-form .el-form-item {
  align-items: center !important;
}

::v-deep .content {
  .table-box {
    width: 50% !important;
  }

  .form {
    width: 48% !important;
    position: relative;
    overflow: hidden;
  }
}

::v-deep .lng {
  .el-form-item__content {
    >span {
      width: 100%;
    }
  }

  .el-input__inner {
    min-width: 90px;
  }
}

::v-deep .lat {
  .el-form-item__content {
    >span {
      width: 100%;
    }
  }

  .el-form-item__label {
    text-align: end;
    min-width: 100px !important;
  }
}

.qrCode {
  text-align: center;
}

.map {
  position: absolute;
  bottom: 0px;
  left: 0;
  width: 100%;
  height: 66%;
  touch-action: none;
}

.noClick {
  cursor: not-allowed;
}

.df {
  display: flex;
  align-items: center;
  width: 100%;

  // 多选
  i {
    font-size: 30px;
    margin-left: 10px;
    cursor: pointer;
  }
}

.dfs {
  ::v-deep .el-form-item__content {
    display: flex;
    /*flex-direction: column;*/
    flex-wrap: wrap;
    flex-direction: row;
    height: 120px;
    overflow-y: hidden;
  }
}

.tags {
  width: 100%;
  height: 90px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;

  .tag-item {
    height: 30px;
    padding: 5px 10px;
    background-color: #00a1c2;
    border-radius: 8px;
    display: flex;
    align-items: center;
    margin-top: 10px;
    margin-right: 10px;

    i {
      font-size: 14px;
    }
  }
}

::v-deep {
  .el-dialog {

    // margin-top: 10vh !important;
    // min-width: 15%;
    // width: 200px !important;
    // height: auto !important;
    .el-dialog__body {
      max-height: 60vh;
      height: 60vh;
    }
  }
}

.line {
  width: 100%;
  display: flex;
  flex-wrap: nowrap;

  .line-click {
    width: 30px;
    height: 30px;
    background-color: rgb(198, 196, 196);
    display: flex;
    justify-content: center;
    align-items: center;
    border: rgb(214, 214, 214) 1px solid;
    border-radius: 50%;
    margin-bottom: 10px;
    margin-top: 5px;
    margin-left: 5px;
    cursor: pointer;
    position: absolute;
    right: 33px;
    top: 86px;

    .el-icon-minus {
      color: white;
    }
  }
}

.line-click {
  width: 30px;
  height: 30px;
  background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  border: rgb(214, 214, 214) 1px solid;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  position: absolute;
  right: 33px;
  top: 86px;
  cursor: pointer;

  .el-icon-plus {
    color: white;
  }
}

.line-clicks {
  width: 30px;
  height: 30px;
  // background-color: rgb(198, 196, 196);
  display: flex;
  justify-content: center;
  align-items: center;
  // border: rgb(214, 214, 214) 1px solid;
  color: red;
  border-radius: 50%;
  margin-bottom: 10px;
  margin-top: 5px;
  margin-left: 20px;
  text-decoration: underline;
  text-underline-position: under;
  position: relative;
  right: 0;
  cursor: pointer;
}

.w100p {
  flex-wrap: wrap;

  >div {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

::v-deep .divider {
  position: absolute;
  top: -25px;

  .el-divider__text {
    background-color: #f0f3f7;
    padding: 0 10px;
    font-size: 18px;
    font-weight: 400;
  }
}
</style>
